
import { defineStore } from "pinia";
import { ref,computed } from "vue";
import { useUserStore } from "./user";
import { ElMessage } from "element-plus";
import { insertCartAPI,findNewCartListAPI ,delCartAPI} from "@/apis/cart";

export const useCartStore= defineStore('cart',()=>{
  const userStore=useUserStore()
  //登录转态
  const isLogin=computed(()=>userStore.userInfo.token)
    //定义购物车列表
    const cartList=ref([])
    //更新购物车数据
    const updateCart=async ()=>{
        const res=await findNewCartListAPI()
         cartList.value=res.result
    }
    //定义添加购物车
    const addCart=async (goods)=>{
        //加入购物车
      let {skuId,count}=goods
      console.log('88899',isLogin.value)
      //登录状态
      if(isLogin.value){
         await insertCartAPI({skuId, count})
         updateCart()
      }else{
        //若存在在count+1
      const item= cartList.value.find((item)=>goods.skuId===item.skuId)
      if(item){
        //找到了
        item.count++
      }else{
        cartList.value.push(goods)
      }
      }
    }
    //删除购物
    const detelCart=async (skuId)=>{
      //登录状态
      if(isLogin.value){
        //调用删除按钮
      await delCartAPI([skuId])
      updateCart()
      ElMessage.success("已取消");
      }else{
        const idx=cartList.value.findIndex((item)=>item.skuId===skuId)
        cartList.value.splice(idx,1)
      }
    }
    //退出清空购物车
    const delCart=()=>{
      cartList.value=[]
    }
    //总数量
    const allCount=computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    //总价格
    const allPrice=computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))
    //是否全选
    const isAll=computed(()=>cartList.value.every((item)=>item.selected))
    //单选框
    const singleCheck=(skuId,selected)=>{
      const item= cartList.value.find((item)=>item.skuId===skuId)       
      item.selected=selected
    }
    //全选功能
    const allCheck=(selected)=>{
     cartList.value.forEach(item=>item.selected=selected)
    }
    //已选这数量
    const selectedCheck=computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
    //已选择的价格
    const selectedPrice=computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))
    return{
        cartList,
        allCount,
        allPrice,
        isAll,
        selectedCheck,
        selectedPrice,
        addCart,
        detelCart,
        singleCheck,
        allCheck,
        delCart,
        updateCart
    }
},//开启持久化存储
{
    persist: true,
  }
)